package com.zzjson.io.nio.demo;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : cn.zzjson.io.nio.demo</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年03月26日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class NIOServer {
    private int port = 8080;

    private InetSocketAddress inetSocketAddress = null;

    private Selector selector;

    public NIOServer(int port) {
        try {

            this.port = port;
            inetSocketAddress = new InetSocketAddress("localhost", this.port);

            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(inetSocketAddress);
            //设置通道为非阻塞
            serverSocketChannel.configureBlocking(false);

            selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务开始监听 ，端口是：" + this.port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void listener() {
        try {

            while (true) {
                //多少用户在排队
                int selectCount = this.selector.select();
                if (selectCount == 0) {
                    continue;
                }

                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    process(selectionKey);
                    //处理完成之后移除
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void process(SelectionKey selectionKey) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        if (selectionKey.isAcceptable()) {
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
        } else if (selectionKey.isReadable()) {
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
            while (true) {
                int len = socketChannel.read(buffer);
                if (len <= 0) {
                    break;
                }
                buffer.flip();
                System.out.println(len);
                String content = new String(buffer.array(), 0, len);
                System.out.println(content);
                buffer.clear();
                socketChannel.register(selector, SelectionKey.OP_WRITE);
            }

        } else if (selectionKey.isWritable()) {
            SocketChannel channel = (SocketChannel) selectionKey.channel();
            channel.write(ByteBuffer.wrap("hello".getBytes()));
            channel.close();

        }

    }

    public static void main(String[] args) {
        new NIOServer(8080).listener();

    }


}